package com.yang.sso.server.service.userDetils;

import com.yang.sso.server.mapper.UserMapper;
import com.yang.sso.server.model.MyUserDetails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.yang.common.core.constant.SystemConstant;
import org.yang.common.core.model.UserInfo;

import java.util.*;

/**
 * @author zhouyang
 * @version v1.1
 * @date 2024/9/23 09:29
 * @description
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserInfo userInfo = Optional.ofNullable(userMapper.selectUserInfo(username))
                .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
        Set<String> permssions = null;
        if(!userInfo.getRoles().isEmpty()){
            permssions=userInfo.getRoles().containsAll(SystemConstant.SUPER_ROLE)?
                    SystemConstant.SUPER_AUTHORIZE:
                    Optional.ofNullable(userMapper.selectAuthorizeByRoleId(userInfo.getRoles()))
                            .orElse(new HashSet<>());
        }
        return new MyUserDetails(userInfo,permssions);
    }


    public Map<String, Object> getUserInfoMap(String username) throws UsernameNotFoundException {
        try {
            Map<String, Object> map=new HashMap<>();
            map.put("username", username);
            map.put("nickname", "测试");
//            UserInfo userInfo = Optional.ofNullable(userMapper.selectUserInfo(username))
//                    .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
//            Set<String> permssions = Optional.ofNullable(userMapper.selectAuthorizeByRoleId(userInfo.getRoles()))
//                    .orElse(new HashSet<>());
//            userInfo.setPerms(permssions);
//            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(userInfo), new TypeReference<Map<String, Object>>(){});

            return map;
        }catch (Exception e){
            e.printStackTrace();
        }
        throw new UsernameNotFoundException("用户不存在");
    }
}
